package com.ymatou.messageroute.api.service;

import java.util.List;

import com.google.gson.reflect.TypeToken;
import com.ymatou.messageroute.api.parameter.ImMessageBean;
import com.ymatou.messageroute.api.parameter.MessageTaskBean;
import com.ymt.base.YmatouBaseCall;
import com.ymt.core.tool.FormatUtil;
import com.ymttest.utils.EnvSetup;

/**
 * 获取路由消息任务接口Call FreeMaker Template自动生成代码
 */
public class GetScenarioMessageCall extends YmatouBaseCall {
	private static String opurl = "Api/Trading/GetScenarioMessage";

	public GetScenarioMessageCall() {
		super(EnvSetup.getSystemUrl("api_messageroute"), opurl, "GET", "PARAM");
	}

	@Override
	public void addDefHeader() {
		client.addHeader("Accept",
				"text/xml,text/javascript,text/html,application/json");
		client.addHeader("Content-Type", "application/json; charset=UTF-8");
	}

	@SuppressWarnings("unchecked")
	public MessageTaskBean getMessageTask() {
		MessageTaskBean messageTaskBean = null;
		try {
			String returnData = getReturnData();

			//returnData = returnData.substring(1, returnData.length() - 1);

			List<MessageTaskBean> messageTaskBeanList = (List<MessageTaskBean>) FormatUtil
					.GSONToObject(returnData,
							new TypeToken<List<MessageTaskBean>>() {
							}.getType());

			if (messageTaskBeanList.size() == 2) {
				messageTaskBeanList
						.get(0)
						.getMessageToolTasks()
						.addAll(messageTaskBeanList.get(1)
								.getMessageToolTasks());
			}
			messageTaskBean = messageTaskBeanList.get(0);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return messageTaskBean;
	}

	// 取im message 内容
	@SuppressWarnings("unchecked")
	public ImMessageBean getImMessage() {
		ImMessageBean message = null;
		try {
			// 只取 消息IM
			if (getMessageTask().getMessageToolTasks().get(0).getMessageTool() == 2) {
				String imMessage = getMessageTask().getMessageToolTasks()
						.get(0).getMessageBody();
				message = (ImMessageBean) FormatUtil.GSONToObject(imMessage,
						ImMessageBean.class);
			} else if (getMessageTask().getMessageToolTasks().get(1)
					.getMessageTool() == 2) {
				String imMessage = getMessageTask().getMessageToolTasks()
						.get(1).getMessageBody();
				message = (ImMessageBean) FormatUtil.GSONToObject(imMessage,
						ImMessageBean.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return message;
	}
}